import logging
from .xml_builder import XMLBuilder
from .device_controller import DeviceController

class CommandProcessor:
    def __init__(self, config, sip_handler, media_handler, device_controller):
        self.config = config
        self.sip_handler = sip_handler
        self.media_handler = media_handler
        self.device_controller = device_controller
        self.logger = logging.getLogger('CommandProcessor')

    def process_command(self, xml_root):
        """处理所有传入的XML命令"""
        cmd_type = xml_root.find('CmdType').text
        device_id = xml_root.find('DeviceID').text
        sn = xml_root.find('SN').text if xml_root.find('SN') is not None else "0"
        
        self.logger.info(f"处理命令: {cmd_type}, SN: {sn}")
        
        # 命令分派
        handlers = {
            "Catalog": self.handle_catalog_query,
            "DeviceInfo": self.handle_device_info_query,
            "RecordInfo": self.handle_record_query,
            "DeviceControl": self.handle_device_control,
            "Alarm": self.handle_alarm,
            "Broadcast": self.handle_broadcast,
        }
        
        handler = handlers.get(cmd_type)
        if handler:
            handler(xml_root, device_id, sn)
        else:
            self.logger.warning(f"未知命令类型: {cmd_type}")

    def handle_catalog_query(self, xml_root, device_id, sn):
        """处理设备目录查询"""
        channels = self.config['device']['channels']
        response = XMLBuilder.catalog_response(device_id, channels)
        self.sip_handler.send_message(response)

    def handle_device_info_query(self, xml_root, device_id, sn):
        """处理设备信息查询"""
        device_info = {
            "name": "GB28181 Client",
            "manufacturer": self.config['device']['manufacturer'],
            "model": self.config['device']['model'],
            "firmware": self.config['device']['firmware'],
            "channels": self.config['device']['channels']
        }
        response = XMLBuilder.device_info_response(device_id, device_info)
        self.sip_handler.send_message(response)

    def handle_record_query(self, xml_root, device_id, sn):
        """处理录像查询"""
        # 伪代码：从设备获取录像记录
        records = self.device_controller.get_record_list(
            device_id,
            xml_root.find('StartTime').text,
            xml_root.find('EndTime').text
        )
        response = XMLBuilder.playback_response(device_id, records)
        self.sip_handler.send_message(response)

    def handle_device_control(self, xml_root, device_id, sn):
        """处理设备控制命令（PTZ）"""
        try:
            ptz_cmd = xml_root.find('PTZCmd').text
            # 伪代码：发送到硬件控制器
            success = self.device_controller.ptz_control(device_id, ptz_cmd)
            result_code = "OK" if success else "Error"
        except Exception as e:
            self.logger.error(f"PTZ控制失败: {str(e)}")
            result_code = "Error"
        
        response = XMLBuilder.ptz_response(device_id, result_code)
        self.sip_handler.send_message(response)

    def handle_alarm(self, xml_root, device_id, sn):
        """处理报警通知（作为客户端通常只发送不接收）"""
        self.logger.warning("收到报警通知，客户端通常不处理此命令")

    def handle_broadcast(self, xml_root, device_id, sn):
        """处理语音广播命令"""
        self.logger.info("收到语音广播命令")
        # 伪代码：启动语音广播
        self.device_controller.start_broadcast(device_id)